package com.zfl.thread.day02;

class BankCount {

    int balance = 1000;
    static Object lock = new Object();

    public void withdraw(int money) {
        if (money > balance) {
            System.out.println(Thread.currentThread().getName() + "取款失败，余额不足");
            return;
        }
        this.balance -= money;
        System.out.println(Thread.currentThread().getName() + "取了[" + money + "]，余额[" + this.balance + "]");
    }

    public void deposit(int money) {
        this.balance += money;
        System.out.println(Thread.currentThread().getName() + "存了[" + money + "]，余额[" + this.balance + "]");
    }
}

public class SynchronizedDemo02 {
    public static void main(String[] args) {
        BankCount bank = new BankCount();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                synchronized (bank) {
                    bank.withdraw(300);
                }

            }
        }, "取款").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                synchronized (bank) {
                    bank.deposit(200);
                }
            }
        }, "存款").start();
    }
}
